package edu.ccut.saturn.component.loader.data;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import edu.ccut.saturn.component.SaturnComponentException;

public class SqlItemLoaderFactory {

	private static final String SQLITEM_TYPE_FILE_NAME = "sqlItem_type.properties";

	private static SqlItemLoaderFactory instance;

	static {
		instance = new SqlItemLoaderFactory();
	}

	private Map<String, Class<?>> sqlItemLoaderClassMap;

	private SqlItemLoaderFactory() {
		loadDirectoryClass();
	}

	/**
	 * 获得<code>SaturnDirectoryFactory</code>的单态实例
	 * 
	 * @return
	 */
	public static SqlItemLoaderFactory getInstance() {
		return instance;
	}

	/**
	 * 创建路径资源实例的方法。根据传入的参数type判断要创建哪种类型的路径资源实例。
	 * 
	 * @param version
	 *            待创建的路径资源实例的版本信息
	 * @param description
	 *            待创建的路径资源实例的描述信息
	 * @param type
	 *            待创建的路径资源实例的类型信息
	 * @param time
	 *            待创建的路径资源实例的创建时间
	 * @return
	 * @throws SaturnComponentException
	 */
	public ISqlItemInfoLoader createSqlItemInfoLoader(String elementName)
			throws SaturnComponentException {

		try {

			if (this.sqlItemLoaderClassMap.containsKey(elementName)) {
				Class<?> itemLoaderClass = this.sqlItemLoaderClassMap
						.get(elementName);

				ISqlItemInfoLoader sqlItemInfoLoader = (ISqlItemInfoLoader) itemLoaderClass
						.newInstance();

				return sqlItemInfoLoader;
			}

		} catch (InstantiationException e) {
			e.printStackTrace();

		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	private void loadDirectoryClass() {
		Properties properties = new Properties();
		InputStream in = null;

		try {
			in = SqlItemLoaderFactory.class
					.getResourceAsStream(SQLITEM_TYPE_FILE_NAME);

			properties.load(in);

		} catch (IOException e) {
			e.printStackTrace();

		} finally {

			if (in != null) {

				try {
					in.close();

				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		this.sqlItemLoaderClassMap = new HashMap<String, Class<?>>();

		for (Enumeration propertyNames = properties.propertyNames(); propertyNames
				.hasMoreElements();) {

			String key = (String) propertyNames.nextElement();
			String className = properties.getProperty(key);

			try {
				this.sqlItemLoaderClassMap.put(key, Class.forName(className));

			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
	}
}
